// src/components/PaginationControls.tsx
"use client"; // 必须是客户端组件才能使用 Hooks

import { useRouter, useSearchParams } from "next/navigation";
import React from "react";

interface PaginationControlsProps {
  currentPage: number;
  totalPages: number;
  limit: number;
}

export default function PaginationControls({
  currentPage,
  totalPages,
  limit,
}: PaginationControlsProps) {
  const router = useRouter();
  const searchParams = useSearchParams();

  // 核心函数：根据页码跳转，并保持 limit 不变
  const handlePageChange = (newPage: number) => {
    if (newPage < 1 || newPage > totalPages) return;

    // 1. 创建新的 URLSearchParams 对象
    const params = new URLSearchParams(searchParams.toString());

    // 2. 更新 page 参数
    params.set("page", newPage.toString());
    params.set("limit", limit.toString());

    // 3. 导航到新 URL (Next.js 会自动触发 Server Component 重新渲染)
    router.push(`/list?${params.toString()}`);
  };

  return (
    <div className="flex justify-center space-x-4 mt-8">
      {/* 上一页按钮 */}
      <button
        onClick={() => handlePageChange(currentPage - 1)}
        disabled={currentPage <= 1}
        className={`px-4 py-2 rounded transition-colors ${
          currentPage <= 1
            ? "bg-gray-200 text-gray-500 cursor-not-allowed"
            : "bg-blue-500 text-white hover:bg-blue-600"
        }`}
      >
        &lt; 上一页
      </button>

      {/* 页码显示 */}
      <span className="self-center text-lg font-semibold">
        {currentPage} / {totalPages}
      </span>

      {/* 下一页按钮 */}
      <button
        onClick={() => handlePageChange(currentPage + 1)}
        disabled={currentPage >= totalPages}
        className={`px-4 py-2 rounded transition-colors ${
          currentPage >= totalPages
            ? "bg-gray-200 text-gray-500 cursor-not-allowed"
            : "bg-blue-500 text-white hover:bg-blue-600"
        }`}
      >
        下一页 &gt;
      </button>
    </div>
  );
}
